package com.imooc.momo_app;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.nfc.Tag;
import android.os.*;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @ClassName: OtherActivity
 * @Author: Jie Li
 * @Date 2019-11-21 16:54
 * @Description: TODO
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2019</p>
 **/
public class OtherActivity extends AppCompatActivity {
    private Button startOther;
    private Handler mHandlerTwo;
    public static final int DOWNLOAD_MESSAGE_CODE = 100001;
    public static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002;
    private static final String TAG = "MainActivity";
    public  static final int CODE = 123;

    private TextView mResultTextView;
    private ImageView mDiglettImageView;
    private  Button mStarrButton;

    public int[][] mPosition = new  int[][]{
            {342,180},{432,880},
            {521,256},{429,780},
            {456,976},{145,665},
            {123,678},{564,567},
    };

    private  int mTotalCount;
    private  int mSuccessCount;

    public static final int MAX_COUNT = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        //启动另外一个activity
        startOther = findViewById(R.id.mainbutton);
        startOther.setOnClickListener(new OtherActivity.StartListener());
        final TextView textView = findViewById(R.id.handlerTexiview);

        final ProgressBar progressBar = findViewById(R.id.progressBar);

        /**
         * 主线程 -->start
         * 点击按钮 |
         * 发起下载 |
         * 开启子线程做下载 |
         * 下载完成后通知主线程 | -->主线程更新进度条
         */

        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        download("http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk");
                    }
                }).start();

            }
        });

        mHandlerTwo =  new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what){
                    case DOWNLOAD_MESSAGE_CODE:
                        progressBar.setProgress((Integer) msg.obj);
                    case DOWNLOAD_MESSAGE_FAIL_CODE:
                        progressBar.setProgress((Integer) msg.obj);
                        break;
                }
            }
        };

        //创建Handler
        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            @SuppressLint("SetTextI18n")
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //处理消息
                Log.d(TAG, "handleMessage:" + msg.what);
                if (msg.what == 1002) {
                    textView.setText("我的内容被更新了" + msg.arg1 + msg.arg2 + msg.obj);

                }
            }
        };

        findViewById(R.id.handlerButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(1001);
                        Message message = Message.obtain();
                        message.what = 1002;
                        message.arg1 = 1003;
                        message.arg2 = 1004;
                        message.obj = OtherActivity.this;
                        handler.sendMessage(message);
                        //在多长时间之后发送消息
                        handler.sendMessageAtTime(message, SystemClock.uptimeMillis() + 1000);
                        //
                        handler.sendMessageDelayed(message, 2000);
                        final Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                int a = 1 + 2 + 3;
                            }
                        };
                        handler.post(runnable);
                        runnable.run();
                        handler.postDelayed(runnable, 2000);
                        runnable.run();
                    }
                }).start();
            }
        });
    }

    class StartListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            // 当点击事件触发后执行，启动OtherActivity
            //创建一个Intent对象
            Intent intent = new Intent();
            //调用setClass方法指定启动某一个Activity
            intent.setClass(OtherActivity.this, MainActivity.class);
            //调用startActivity
            startActivity(intent);

        }

    }

    private void download(String appUrl) {
        try {
            URL url = new URL(appUrl);
            URLConnection urlConnection = url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();

            /**
             * 获取文件的总长度
             */
            int contentLength = urlConnection.getContentLength();

            String downloadFolderName = Environment.getExternalStorageDirectory()
                    + File.separator + "imooc" + File.separator;

            File file = new File(downloadFolderName);
            if (!file.exists()) {
                file.mkdir();
            }

            String fileName = downloadFolderName + "imooc.apk";

            File apkFile = new File(fileName);

            if (apkFile.exists()) {
                apkFile.delete();
            }

            int downloadSize = 0;
            byte[] bytes = new byte[1024];

            int length = 0;

            OutputStream outputStream = new FileOutputStream(fileName);
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
                downloadSize += length;
                /**
                 * update UI
                 */

                Message message = Message.obtain();
                message.obj = downloadSize * 100 / contentLength;
                message.what = DOWNLOAD_MESSAGE_CODE;
                mHandlerTwo.sendMessage(message);
            }
            inputStream.close();
            outputStream.close();

        } catch (MalformedURLException e) {
            notifyDownloadFaild();
            e.printStackTrace();
        } catch (IOException e) {
            notifyDownloadFaild();
            e.printStackTrace();
        }
    }

    private void notifyDownloadFaild() {
        Message message = Message.obtain();
        message.what = DOWNLOAD_MESSAGE_FAIL_CODE;
        mHandlerTwo.sendMessage(message);
    }
}
